package task;

import app.FileMeta;
import util.DBUtil;

import java.io.File;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 根据表单获取的文件路径和文件名搜索指定文件，支持模糊查找
 * @Author: yuisama
 * @Date: 2022/6/18 14:17
 * @Description:
 */
public class FileSearch {
    /**
     * 根据文件路径和检索的内容在db中检索文件信息，支持模糊查找
     * @param dir 文件路径
     * @param content 搜索的关键字
     * @return
     */
    public static List<FileMeta> search(String dir, String content) {
        List<FileMeta> metas = new ArrayList<>();
        Connection connection = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        try {
            connection = DBUtil.getConnection();
            String sql = "select name,path,is_directory,size,last_modified" +
                    " from file_meta where" +
                    " (path = ? or path like ?)";
            if (content != null && content.trim().length() != 0) {
                sql += " and (name like ? or pinyin like ? or pinyin_first like ?)";
            }
            ps = connection.prepareStatement(sql);
            ps.setString(1,dir);
            ps.setString(2,dir + File.separator + "%");
            if (content != null && content.trim().length() != 0) {
                ps.setString(3,"%" + content + "%");
                ps.setString(4,"%" + content + "%");
                ps.setString(5,"%" + content + "%");
            }
            rs = ps.executeQuery();
            while (rs.next()) {
                String name = rs.getString("name");
                String path = rs.getString("path");
                boolean is_directory = rs.getBoolean("is_directory");
                long size = rs.getLong("size");
                Date date = new java.util.Date(rs.getTimestamp("last_modified").getTime());
                FileMeta meta = new FileMeta(name,path,is_directory,size,date);
//                System.out.println("检索到文件信息 : name = " + name + ",path = " + path);
                metas.add(meta);
            }
        }catch (SQLException e) {
            throw new RuntimeException("文件检索出错。" + e);
        }finally {
            DBUtil.close(rs,ps);
        }
        return metas;
    }
}
